Skip to content

Conversation

@elad12390
Copy link

Fixes #266

Problem

When using SDK MCP servers (create_sdk_mcp_server()), queries crash with:

CLIConnectionError: ProcessTransport is not ready for writing

This error occurs in _internal/query.py at lines 303 and 315 when control request handlers try to write responses.

Root Cause

Control requests are handled in separate background tasks via _tg.start_soon(self._handle_control_request, request) (line 183).

During query cleanup, the transport is marked as not ready (self._ready = False) and streams are closed. However, pending control request handler tasks may still be running and attempt to write their responses, causing the crash.

Race condition timeline:

  1. Control request received → handler task spawned
  2. Query completes or errors → cleanup begins
  3. Transport marked as not ready → streams closed
  4. Handler task tries to write response → CRASH

Solution

Wrap the transport.write() calls in try-except blocks to gracefully handle when the transport is not ready. This allows control request handlers to fail silently if they run during cleanup, rather than crashing the entire query.

Changes

File: src/claude_agent_sdk/_internal/query.py

Change 1: Success response write (line 303)

Before:

await self.transport.write(json.dumps(success_response) + "\n")

After:

try:
    await self.transport.write(json.dumps(success_response) + "\n")
except Exception as write_err:
    # Transport not ready (likely during cleanup) - log but don't fail
    logger.debug(
        f"Could not write control response (transport not ready): {write_err}"
    )

Change 2: Error response write (line 315)

Before:

await self.transport.write(json.dumps(error_response) + "\n")

After:

try:
    await self.transport.write(json.dumps(error_response) + "\n")
except Exception as write_err:
    # Transport not ready (likely during cleanup) - log but don't fail
    logger.debug(
        f"Could not write error response (transport not ready): {write_err}"
    )

Testing

Tested with SDK MCP servers using the scenario from issue #266:

  1. Create SDK MCP server with custom tool
  2. Run query that uses the tool
  3. Verify no crash during cleanup

Before fix: Consistent crash with ProcessTransport is not ready for writing
After fix: Clean execution, graceful cleanup

Impact

Additional Context

This fix was discovered and tested while building a production application using Claude Agent SDK with custom MCP tools. The race condition was consistently reproducible and this fix eliminates the crash entirely.

The issue reporter in #266 did extensive debugging work to identify this bug. This PR provides the fix they were looking for.

Fixes anthropics#266

When using SDK MCP servers, control request handlers were crashing with
'ProcessTransport is not ready for writing' error. This happened because
control requests are handled in background tasks that may try to write
responses after the transport is closed during cleanup.

This fix wraps transport.write() calls in try-except blocks to gracefully
handle cases where the transport is not ready, allowing queries to complete
successfully instead of crashing.

Changes:
- Wrap success response write in try-except (line 303)
- Wrap error response write in try-except (line 315)
- Log debug message when write fails due to transport not ready

Impact:
- Fixes SDK MCP server tool execution
- Low risk: only affects error handling during cleanup
- Backward compatible: no API changes
@dltn
Copy link
Collaborator

dltn commented Dec 1, 2025

#380

@dltn
Copy link
Collaborator

dltn commented Dec 1, 2025

This PR adds more graceful error handling, but doesn't fix the stream closure. Fixed in #380

@dltn dltn closed this Dec 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SDK MCP Servers fail with "ProcessTransport is not ready for writing" error - Tool functions never execute

2 participants